package com.qfedu.fmmall.service.job;


import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfig;
import com.qfedu.fmmall.dao.OrdersMapper;
import com.qfedu.fmmall.entity.Orders;
import com.qfedu.fmmall.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class OrderTimeoutCheckJob {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderService orderService;

    private WXPay wxPay = new WXPay(new MyPayConfig());

    @Scheduled(cron = "0/60 * * * * ?")
    public void checkAndCloseOrder()  {
        //1.查询超过30min订单状态为待支付状态的订单
        System.out.println("------------开始查找");

        try {
            Example example = new Example(Orders.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("status","1");
            Date time = new Date(System.currentTimeMillis()-30 * 60 * 1000);
            criteria.andLessThan("createTime",time);
            List<Orders> orders = ordersMapper.selectByExample(criteria);
            //2.访问微信平台接口，确认当前订单最终的支付状态
            for (int i = 0; i < orders.size(); i++) {
                Orders order = orders.get(i);
                HashMap<String,String> params = new HashMap<>();
                params.put("out_trade_no",order.getOrderId());
                //查询订单支付状态
                Map<String, String> orderQuery = wxPay.orderQuery(params);
                if("SUCCESS".equalsIgnoreCase(orderQuery.get("trade_state"))){
                    //如果支付成功，将订单修改为已支付/待发货
                    Orders updateOrder = new Orders();
                    updateOrder.setOrderId(order.getOrderId());
                    updateOrder.setStatus("2");
                    ordersMapper.updateByPrimaryKeySelective(updateOrder);
                }else{
                    //未支付，取消订单
                    //1。先去微信平台关闭该订单的支付通道
                    Map<String, String> map = wxPay.closeOrder(params);
                    System.out.println("取消结果"+map);
                    //2。关闭订单
                    orderService.closeOrder(order.getOrderId());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }


}
